<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>SpringCloud的LoadBalance源码分析 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第二十篇博客–SpringCloud的LoadBalance源码分析 相关核心类LoadBalancedLoadBalancerClientLoadBalancerAutoConfigurationLoadBalancerInterceptorRibbonAutoConfigurationRibbonClassesConditionsAllNestedConditionsAbs">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringCloud的LoadBalance源码分析">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/06/05/springCloud的LoadBalance源码分析/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第二十篇博客–SpringCloud的LoadBalance源码分析 相关核心类LoadBalancedLoadBalancerClientLoadBalancerAutoConfigurationLoadBalancerInterceptorRibbonAutoConfigurationRibbonClassesConditionsAllNestedConditionsAbs">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-06-06T02:32:01.351Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringCloud的LoadBalance源码分析">
<meta name="twitter:description" content="欢迎查看Eetal的第二十篇博客–SpringCloud的LoadBalance源码分析 相关核心类LoadBalancedLoadBalancerClientLoadBalancerAutoConfigurationLoadBalancerInterceptorRibbonAutoConfigurationRibbonClassesConditionsAllNestedConditionsAbs">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-springCloud的LoadBalance源码分析" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/06/05/springCloud的LoadBalance源码分析/" class="article-date">
  	<time datetime="2019-06-05T07:31:59.979Z" itemprop="datePublished">2019-06-05</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      SpringCloud的LoadBalance源码分析
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第二十篇博客–SpringCloud的LoadBalance源码分析</p>
<h2 id="相关核心类"><a href="#相关核心类" class="headerlink" title="相关核心类"></a>相关核心类</h2><p>LoadBalanced<br>LoadBalancerClient<br>LoadBalancerAutoConfiguration<br>LoadBalancerInterceptor<br>RibbonAutoConfiguration<br>RibbonClassesConditions<br>AllNestedConditions<br>AbstractNestedCondition<br>AbstractNestedCondition.MemberMatchOutcomes<br>AbstractNestedCondition.MemberConditions<br>SpringBootCondition<br>ConditionOutcome</p>
<h2 id="LoadBalanced注解与功能"><a href="#LoadBalanced注解与功能" class="headerlink" title="LoadBalanced注解与功能"></a>LoadBalanced注解与功能</h2><p>通过在创建的RestTemplate上加入LoadBalanced注解，则该RestTemplate会自动成为负载均衡的RestTeplate，请求的url的hostname会作为服务名称去解析<br>用法如下<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@LoadBalanced</span><br><span class="line">@Bean</span><br><span class="line">   public RestTemplate <span class="function"><span class="title">restTemplate</span></span>() &#123;</span><br><span class="line">       <span class="built_in">return</span> new RestTemplate();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">public String <span class="function"><span class="title">requestTest</span></span>()&#123;</span><br><span class="line">String url = <span class="string">"http://8781-eurekaClient/getClient2Info"</span>;</span><br><span class="line"><span class="built_in">return</span> restTemplate.getForObject(url, String.class);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>等价于以下写法<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@Autowired</span><br><span class="line">	RestTemplate restTemplate;</span><br><span class="line">	</span><br><span class="line">	@Autowired</span><br><span class="line">    private LoadBalancerClient client;</span><br><span class="line">	</span><br><span class="line">	@RequestMapping(<span class="string">"/getProviderInfo"</span>)</span><br><span class="line">	public String <span class="function"><span class="title">getProviderInfo</span></span>() &#123;</span><br><span class="line">		ServiceInstance instance = client.choose(<span class="string">"8780-eurekaClient"</span>);</span><br><span class="line">        String url = <span class="string">"http://"</span> + instance.getHost() + <span class="string">":"</span> + instance.getPort() + <span class="string">"/getInfo"</span>;</span><br><span class="line">        <span class="built_in">return</span> restTemplate.getForObject(url, String.class);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h2><p>1.LoadBalanced注解<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">@Target(&#123; ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD &#125;)</span><br><span class="line">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="line">@Documented</span><br><span class="line">@Inherited</span><br><span class="line">@Qualifier</span><br><span class="line">public @interface LoadBalanced &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里注意，该注解被标记了@Qualifier注解，后续使用@Autowired注解注入时，如果注解的属性也被LoadBalanced注解，则只装载一样被LoadBalanced注解的符合autowired的对象<br>2.LoadBalnceAutoConfigure<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@ConditionalOnClass(RestTemplate.class)</span><br><span class="line">@ConditionalOnBean(LoadBalancerClient.class)</span><br><span class="line">@EnableConfigurationProperties(LoadBalancerRetryProperties.class)</span><br><span class="line">public class LoadBalancerAutoConfiguration &#123;</span><br><span class="line"></span><br><span class="line">	@LoadBalanced</span><br><span class="line">	@Autowired(required = <span class="literal">false</span>)</span><br><span class="line">	private List&lt;RestTemplate&gt; restTemplates = Collections.emptyList();</span><br><span class="line"></span><br><span class="line">	@Autowired(required = <span class="literal">false</span>)</span><br><span class="line">	private List&lt;LoadBalancerRequestTransformer&gt; transformers = Collections.emptyList();</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(</span><br><span class="line">			final ObjectProvider&lt;List&lt;RestTemplateCustomizer&gt;&gt; restTemplateCustomizers) &#123;</span><br><span class="line">		<span class="built_in">return</span> () -&gt; restTemplateCustomizers.ifAvailable(customizers -&gt; &#123;</span><br><span class="line">			<span class="keyword">for</span> (RestTemplate restTemplate : LoadBalancerAutoConfiguration.this.restTemplates) &#123;</span><br><span class="line">				<span class="keyword">for</span> (RestTemplateCustomizer customizer : customizers) &#123;</span><br><span class="line">					customizer.customize(restTemplate);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	@ConditionalOnMissingBean</span><br><span class="line">	public LoadBalancerRequestFactory loadBalancerRequestFactory(</span><br><span class="line">			LoadBalancerClient loadBalancerClient) &#123;</span><br><span class="line">		<span class="built_in">return</span> new LoadBalancerRequestFactory(loadBalancerClient, this.transformers);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Configuration</span><br><span class="line">	@ConditionalOnMissingClass(<span class="string">"org.springframework.retry.support.RetryTemplate"</span>)</span><br><span class="line">	static class LoadBalancerInterceptorConfig &#123;</span><br><span class="line"></span><br><span class="line">		@Bean</span><br><span class="line">		public LoadBalancerInterceptor ribbonInterceptor(</span><br><span class="line">				LoadBalancerClient loadBalancerClient,</span><br><span class="line">				LoadBalancerRequestFactory requestFactory) &#123;</span><br><span class="line">			<span class="built_in">return</span> new LoadBalancerInterceptor(loadBalancerClient, requestFactory);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@Bean</span><br><span class="line">		@ConditionalOnMissingBean</span><br><span class="line">		public RestTemplateCustomizer restTemplateCustomizer(</span><br><span class="line">				final LoadBalancerInterceptor loadBalancerInterceptor) &#123;</span><br><span class="line">			<span class="built_in">return</span> restTemplate -&gt; &#123;</span><br><span class="line">				List&lt;ClientHttpRequestInterceptor&gt; list = new ArrayList&lt;&gt;(</span><br><span class="line">						restTemplate.getInterceptors());</span><br><span class="line">				list.add(loadBalancerInterceptor);</span><br><span class="line">				restTemplate.setInterceptors(list);</span><br><span class="line">			&#125;;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>@ConditionalOnClass(RestTemplate.class)<br>@ConditionalOnBean(LoadBalancerClient.class)<br>这个配置类依赖于加载RestTemplate类以及创建了LoadBalancerClient对象<br>其中会创建一个RestTemplateCustomizer提供给上方创建智能初始化的bean，该bean初始化过程会使用这个RestTemplateCustomizer，为每个loadBalanced注解的restTemplate加上一个负载均衡的拦截器<br>如果配置生效，根据前面对LoadBalanced注解了解，此处的集合成员restTemplates就是IOC容器中，被LoadBalanced注解了的RestTemplate<br>RestTemplate是我们手动的导入，接下来查找LoadBalancerClient对象，在RibbonAutoConfiguration中<br>拦截器<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor &#123;</span><br><span class="line"></span><br><span class="line">	private LoadBalancerClient loadBalancer;</span><br><span class="line"></span><br><span class="line">	private LoadBalancerRequestFactory requestFactory;</span><br><span class="line"></span><br><span class="line">	public LoadBalancerInterceptor(LoadBalancerClient loadBalancer) &#123;</span><br><span class="line">		// <span class="keyword">for</span> backwards compatibility</span><br><span class="line">		this(loadBalancer, new LoadBalancerRequestFactory(loadBalancer));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,</span><br><span class="line">			final ClientHttpRequestExecution execution) throws IOException &#123;</span><br><span class="line">		final URI originalUri = request.getURI();</span><br><span class="line">		String serviceName = originalUri.getHost();</span><br><span class="line">		Assert.state(serviceName != null,</span><br><span class="line">				<span class="string">"Request URI does not contain a valid hostname: "</span> + originalUri);</span><br><span class="line">		<span class="built_in">return</span> this.loadBalancer.execute(serviceName,</span><br><span class="line">				this.requestFactory.createRequest(request, body, execution));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Ribbon自动配置<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@Conditional(RibbonAutoConfiguration.RibbonClassesConditions.class)</span><br><span class="line">@RibbonClients</span><br><span class="line">@AutoConfigureAfter(name = <span class="string">"org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration"</span>)</span><br><span class="line">@AutoConfigureBefore(&#123; LoadBalancerAutoConfiguration.class,</span><br><span class="line">		AsyncLoadBalancerAutoConfiguration.class &#125;)</span><br><span class="line">@EnableConfigurationProperties(&#123; RibbonEagerLoadProperties.class,</span><br><span class="line">		ServerIntrospectorProperties.class &#125;)</span><br><span class="line">public class RibbonAutoConfiguration &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	@Bean</span><br><span class="line">	@ConditionalOnMissingBean(LoadBalancerClient.class)</span><br><span class="line">	public LoadBalancerClient <span class="function"><span class="title">loadBalancerClient</span></span>() &#123;</span><br><span class="line">		<span class="built_in">return</span> new RibbonLoadBalancerClient(springClientFactory());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * &#123;@link AllNestedConditions&#125; that checks that either multiple classes are present.</span><br><span class="line">	 */</span><br><span class="line">	static class RibbonClassesConditions extends AllNestedConditions &#123;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="title">RibbonClassesConditions</span></span>() &#123;</span><br><span class="line">			super(ConfigurationPhase.PARSE_CONFIGURATION);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@ConditionalOnClass(IClient.class)</span><br><span class="line">		static class IClientPresent &#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@ConditionalOnClass(RestTemplate.class)</span><br><span class="line">		static class RestTemplatePresent &#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@ConditionalOnClass(AsyncRestTemplate.class)</span><br><span class="line">		static class AsyncRestTemplatePresent &#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		@ConditionalOnClass(Ribbon.class)</span><br><span class="line">		static class RibbonPresent &#123;</span><br><span class="line"></span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>当IOC容器没有LoadBalancerClient实例时，RibbonAutoConfiguration会自动创建一个Ribbon实现的负载均衡客户端，是其子类<br>这也是为什么springCloud的Eureka客户端会默认使用Ribbon作为负载均衡<br>因为spring-cloud-starter-netflix-eureka-client工程引入依赖了spring-cloud-starter-netflix-ribbon</p>
<p>@Conditional(RibbonAutoConfiguration.RibbonClassesConditions.class)的意思是该要求满足该类中所有condition相关注解(程序加载了对应的四个类)<br>public abstract class AllNestedConditions extends AbstractNestedCondition<br>public abstract class AbstractNestedCondition extends SpringBootCondition implements ConfigurationCondition<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line">public abstract class SpringBootCondition implements Condition &#123;</span><br><span class="line"></span><br><span class="line">	private final Log logger = LogFactory.getLog(getClass());</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public final boolean matches(ConditionContext context,</span><br><span class="line">			AnnotatedTypeMetadata metadata) &#123;</span><br><span class="line">			//成立判断方法</span><br><span class="line">		String classOrMethodName = getClassOrMethodName(metadata);</span><br><span class="line">		try &#123;</span><br><span class="line">			ConditionOutcome outcome = getMatchOutcome(context, metadata);//调用getMatchOutcome</span><br><span class="line">			logOutcome(classOrMethodName, outcome);</span><br><span class="line">			recordEvaluation(context, classOrMethodName, outcome);</span><br><span class="line">			<span class="built_in">return</span> outcome.isMatch();//注意这里，outcome的match属性作为结果</span><br><span class="line">		&#125;</span><br><span class="line">		catch (NoClassDefFoundError ex) &#123;</span><br><span class="line">			throw new IllegalStateException(</span><br><span class="line">					<span class="string">"Could not evaluate condition on "</span> + classOrMethodName + <span class="string">" due to "</span></span><br><span class="line">							+ ex.getMessage() + <span class="string">" not "</span></span><br><span class="line">							+ <span class="string">"found. Make sure your own configuration does not rely on "</span></span><br><span class="line">							+ <span class="string">"that class. This can also happen if you are "</span></span><br><span class="line">							+ <span class="string">"@ComponentScanning a springframework package (e.g. if you "</span></span><br><span class="line">							+ <span class="string">"put a @ComponentScan in the default package by mistake)"</span>,</span><br><span class="line">					ex);</span><br><span class="line">		&#125;</span><br><span class="line">		catch (RuntimeException ex) &#123;</span><br><span class="line">			throw new IllegalStateException(</span><br><span class="line">					<span class="string">"Error processing condition on "</span> + getName(metadata), ex);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	......</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public abstract class AbstractNestedCondition extends SpringBootCondition</span><br><span class="line">		implements ConfigurationCondition &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public ConditionOutcome getMatchOutcome(ConditionContext context,</span><br><span class="line">			AnnotatedTypeMetadata metadata) &#123;</span><br><span class="line">		String className = getClass().getName();</span><br><span class="line">		MemberConditions memberConditions = new MemberConditions(context, className);</span><br><span class="line">		MemberMatchOutcomes memberOutcomes = new MemberMatchOutcomes(memberConditions);</span><br><span class="line">		<span class="built_in">return</span> getFinalMatchOutcome(memberOutcomes);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	protected static class MemberMatchOutcomes &#123;</span><br><span class="line"></span><br><span class="line">		private final List&lt;ConditionOutcome&gt; all;</span><br><span class="line"></span><br><span class="line">		private final List&lt;ConditionOutcome&gt; matches;</span><br><span class="line"></span><br><span class="line">		private final List&lt;ConditionOutcome&gt; nonMatches;</span><br><span class="line"></span><br><span class="line">		public MemberMatchOutcomes(MemberConditions memberConditions) &#123;</span><br><span class="line">			this.all = Collections.unmodifiableList(memberConditions.getMatchOutcomes());</span><br><span class="line">			List&lt;ConditionOutcome&gt; matches = new ArrayList&lt;&gt;();</span><br><span class="line">			List&lt;ConditionOutcome&gt; nonMatches = new ArrayList&lt;&gt;();</span><br><span class="line">			<span class="keyword">for</span> (ConditionOutcome outcome : this.all) &#123;</span><br><span class="line">				//是否满足加到不同属性集合</span><br><span class="line">				(outcome.isMatch() ? matches : nonMatches).add(outcome);</span><br><span class="line">			&#125;</span><br><span class="line">			this.matches = Collections.unmodifiableList(matches);</span><br><span class="line">			this.nonMatches = Collections.unmodifiableList(nonMatches);</span><br><span class="line">		&#125;</span><br><span class="line">		......</span><br><span class="line"></span><br><span class="line">	&#125;	</span><br><span class="line">&#125;</span><br><span class="line">public abstract class AllNestedConditions extends AbstractNestedCondition &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	protected ConditionOutcome getFinalMatchOutcome(MemberMatchOutcomes memberOutcomes) &#123;</span><br><span class="line">		boolean match = hasSameSize(memberOutcomes.getMatches(), memberOutcomes.getAll());</span><br><span class="line">		//match就是判断结果</span><br><span class="line">		List&lt;ConditionMessage&gt; messages = new ArrayList&lt;&gt;();</span><br><span class="line">		messages.add(ConditionMessage.forCondition(<span class="string">"AllNestedConditions"</span>)</span><br><span class="line">				.because(memberOutcomes.getMatches().size() + <span class="string">" matched "</span></span><br><span class="line">						+ memberOutcomes.getNonMatches().size() + <span class="string">" did not"</span>));</span><br><span class="line">		<span class="keyword">for</span> (ConditionOutcome outcome : memberOutcomes.getAll()) &#123;</span><br><span class="line">			messages.add(outcome.getConditionMessage());</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> new ConditionOutcome(match, ConditionMessage.of(messages));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	private boolean hasSameSize(List&lt;?&gt; list1, List&lt;?&gt; list2) &#123;</span><br><span class="line">		<span class="built_in">return</span> list1.size() == list2.size();</span><br><span class="line">	&#125;</span><br><span class="line">	......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>ribbon的loadBalanceClient实现类<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br></pre></td><td class="code"><pre><span class="line">public class RibbonLoadBalancerClient implements LoadBalancerClient &#123;</span><br><span class="line"></span><br><span class="line">	private SpringClientFactory clientFactory;</span><br><span class="line"></span><br><span class="line">	public RibbonLoadBalancerClient(SpringClientFactory clientFactory) &#123;</span><br><span class="line">		this.clientFactory = clientFactory;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public URI reconstructURI(ServiceInstance instance, URI original) &#123;</span><br><span class="line">		Assert.notNull(instance, <span class="string">"instance can not be null"</span>);</span><br><span class="line">		String serviceId = instance.getServiceId();</span><br><span class="line">		RibbonLoadBalancerContext context = this.clientFactory</span><br><span class="line">				.getLoadBalancerContext(serviceId);</span><br><span class="line"></span><br><span class="line">		URI uri;</span><br><span class="line">		Server server;</span><br><span class="line">		<span class="keyword">if</span> (instance instanceof RibbonServer) &#123;</span><br><span class="line">			RibbonServer ribbonServer = (RibbonServer) instance;</span><br><span class="line">			server = ribbonServer.getServer();</span><br><span class="line">			uri = updateToSecureConnectionIfNeeded(original, ribbonServer);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> &#123;</span><br><span class="line">			server = new Server(instance.getScheme(), instance.getHost(),</span><br><span class="line">					instance.getPort());</span><br><span class="line">			IClientConfig clientConfig = clientFactory.getClientConfig(serviceId);</span><br><span class="line">			ServerIntrospector serverIntrospector = serverIntrospector(serviceId);</span><br><span class="line">			uri = updateToSecureConnectionIfNeeded(original, clientConfig,</span><br><span class="line">					serverIntrospector, server);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> context.reconstructURIWithServer(server, uri);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public ServiceInstance choose(String serviceId) &#123;</span><br><span class="line">		<span class="built_in">return</span> choose(serviceId, null);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * New: Select a server using a <span class="string">'key'</span>.</span><br><span class="line">	 * @param serviceId of the service to choose an instance <span class="keyword">for</span></span><br><span class="line">	 * @param hint to specify the service instance</span><br><span class="line">	 * @<span class="built_in">return</span> the selected &#123;@link ServiceInstance&#125;</span><br><span class="line">	 */</span><br><span class="line">	public ServiceInstance choose(String serviceId, Object hint) &#123;</span><br><span class="line">		Server server = getServer(getLoadBalancer(serviceId), hint);</span><br><span class="line">		<span class="keyword">if</span> (server == null) &#123;</span><br><span class="line">			<span class="built_in">return</span> null;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> new RibbonServer(serviceId, server, isSecure(server, serviceId),</span><br><span class="line">				serverIntrospector(serviceId).getMetadata(server));</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public &lt;T&gt; T execute(String serviceId, LoadBalancerRequest&lt;T&gt; request)</span><br><span class="line">			throws IOException &#123;</span><br><span class="line">		<span class="built_in">return</span> execute(serviceId, request, null);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	/**</span><br><span class="line">	 * New: Execute a request by selecting server using a <span class="string">'key'</span>. The hint will have to be</span><br><span class="line">	 * the last parameter to not mess with the `execute(serviceId, ServiceInstance,</span><br><span class="line">	 * request)` method. This somewhat breaks the fluent coding style when using a lambda</span><br><span class="line">	 * to define the LoadBalancerRequest.</span><br><span class="line">	 * @param &lt;T&gt; returned request execution result <span class="built_in">type</span></span><br><span class="line">	 * @param serviceId id of the service to execute the request to</span><br><span class="line">	 * @param request to be executed</span><br><span class="line">	 * @param hint used to choose appropriate &#123;@link Server&#125; instance</span><br><span class="line">	 * @<span class="built_in">return</span> request execution result</span><br><span class="line">	 * @throws IOException executing the request may result <span class="keyword">in</span> an &#123;@link IOException&#125;</span><br><span class="line">	 */</span><br><span class="line">	public &lt;T&gt; T execute(String serviceId, LoadBalancerRequest&lt;T&gt; request, Object hint)</span><br><span class="line">			throws IOException &#123;</span><br><span class="line">		ILoadBalancer loadBalancer = getLoadBalancer(serviceId);</span><br><span class="line">		Server server = getServer(loadBalancer, hint);</span><br><span class="line">		<span class="keyword">if</span> (server == null) &#123;</span><br><span class="line">			throw new IllegalStateException(<span class="string">"No instances available for "</span> + serviceId);</span><br><span class="line">		&#125;</span><br><span class="line">		RibbonServer ribbonServer = new RibbonServer(serviceId, server,</span><br><span class="line">				isSecure(server, serviceId),</span><br><span class="line">				serverIntrospector(serviceId).getMetadata(server));</span><br><span class="line"></span><br><span class="line">		<span class="built_in">return</span> execute(serviceId, ribbonServer, request);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public &lt;T&gt; T execute(String serviceId, ServiceInstance serviceInstance,</span><br><span class="line">			LoadBalancerRequest&lt;T&gt; request) throws IOException &#123;</span><br><span class="line">		Server server = null;</span><br><span class="line">		<span class="keyword">if</span> (serviceInstance instanceof RibbonServer) &#123;</span><br><span class="line">			server = ((RibbonServer) serviceInstance).getServer();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (server == null) &#123;</span><br><span class="line">			throw new IllegalStateException(<span class="string">"No instances available for "</span> + serviceId);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		RibbonLoadBalancerContext context = this.clientFactory</span><br><span class="line">				.getLoadBalancerContext(serviceId);</span><br><span class="line">		RibbonStatsRecorder statsRecorder = new RibbonStatsRecorder(context, server);</span><br><span class="line"></span><br><span class="line">		try &#123;</span><br><span class="line">			T returnVal = request.apply(serviceInstance);</span><br><span class="line">			statsRecorder.recordStats(returnVal);</span><br><span class="line">			<span class="built_in">return</span> returnVal;</span><br><span class="line">		&#125;</span><br><span class="line">		// catch IOException and rethrow so RestTemplate behaves correctly</span><br><span class="line">		catch (IOException ex) &#123;</span><br><span class="line">			statsRecorder.recordStats(ex);</span><br><span class="line">			throw ex;</span><br><span class="line">		&#125;</span><br><span class="line">		catch (Exception ex) &#123;</span><br><span class="line">			statsRecorder.recordStats(ex);</span><br><span class="line">			ReflectionUtils.rethrowRuntimeException(ex);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">return</span> null;</span><br><span class="line">	&#125;</span><br><span class="line">	......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/06/20/java-rmi源码解析/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          java-rmi源码解析
        
      </div>
    </a>
  
  
    <a href="/blog/2019/05/26/使用HandlerInterceptor和RateLimiter进行限流/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">使用HandlerInterceptor和RateLimiter进行限流</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="springCloud的LoadBalance源码分析" data-title="SpringCloud的LoadBalance源码分析" data-url="http://eetal.gitee.io/blog/blog/2019/06/05/springCloud的LoadBalance源码分析/"  data-images="/blog/images/head.jpg" data-content="SpringCloud的LoadBalance源码分析">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>